package testPaperWrongHistory;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lancooznbk.R;
import com.example.lancooznbk.model.result.BaseReviewWrongEntity;
import com.example.lancooznbk.presenter.PaperDef;
import com.example.lancooznbk.view.base.BaseActivity;
import com.example.lancooznbk.view.base.BaseFragment;
import com.example.lancooznbk.view.base.ILoadPaperView;
import com.example.lancooznbk.view.widget.EmptyMainLayout;
import com.example.lancooznbk.view.widget.LoadingDialog;
import com.lancoo.dictionary.activity.DictionaryActicity;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.util.List;

import lancooControl.AndroidBug5497Workaround;
import lancooControl.Control;
import lancooControl.PopupWindowMoreFunction;
import lancooUpLoad.ChangeStuFavouritePresenter;
import lancooUpLoad.PaperInfor;
import testPaperWrongHistory.jsonWrongHistory.HistoryWrongQuesJson;
import testPaperWrongHistory.jsonWrongHistory.HistoryWrongQuesPresenter;


/**
 * Created by Administrator on 2017/6/7/007.
 */

public class HistoryWrongQuesPaperActivity extends BaseActivity implements View.OnLayoutChangeListener,ILoadPaperView<List<HistoryWrongQuesJson>> {

    private RelativeLayout RLayoutBackMenu;//返回按钮菜单
    private TextView TvBack;//返回按钮
    private RelativeLayout RLayoutAnswerNumberMenu;//答题号菜单
    private RelativeLayout RLayoutSubmitMenu;//提交菜单
    private TextView TvSubmit;//提交文字
//    private ImageView IvAssess;//分数评判
    private RelativeLayout RLayoutMoreFouctionMenu;//更多功能菜单
    private TextView TvTimeMeter;//计时器

    public static ViewPager VpHistoryWrong;
    private HistoryWrongQuesPaperFragmentAdapter mAdapter;


    public static int lastBigViewPage =0;
    public static int currentBigViewPage = 0;

    private HistoryWrongQuesPresenter mHistoryWrongQuesPresenter;
    public static List<HistoryWrongQuesJson> InforHistoryWrongQues;


    //Activity最外层的Layout视图
    private View activityRootView;
    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;

    private BaseReviewWrongEntity.ModelListBean mWrongEntity;
    public static final  String PAPER_ENTITY = "paperWrongEntity";
    public static final  String PAPER_FROM = "paperFrom";

    public int mQuesOrPaperFrom;

    public  static void launch(BaseFragment mContext, BaseReviewWrongEntity.ModelListBean entity, @PaperDef.PaperFrom int quesFrom){

        PaperInfor.QuesID = entity.getQuesID();
        PaperInfor.QuesFrom = entity.getQuesFrom();
        Log.e("==110===","===QuesID==="+PaperInfor.QuesID);
        Log.e("==110===","===QuesFrom==="+PaperInfor.QuesFrom);

        Bundle bundle = new Bundle();
        bundle.putSerializable(PAPER_ENTITY,entity);
        bundle.putInt(PAPER_FROM,quesFrom);
        Intent intent = new Intent(mContext.getContext(), HistoryWrongQuesPaperActivity.class);
        intent.putExtras(bundle);
        mContext.startActivityForResult(intent,1);
    }

    @Override
    public int attachLayoutRes() {
        return R.layout.activity_test_paper;
    }

    @Override
    protected void initViews() {
        AndroidBug5497Workaround.assistActivity(this);
        mHistoryWrongQuesPresenter = new HistoryWrongQuesPresenter(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            mWrongEntity = (BaseReviewWrongEntity.ModelListBean) bundle.getSerializable(PAPER_ENTITY);
            mQuesOrPaperFrom = bundle.getInt(PAPER_FROM);
        }

        //核心代码.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        currentBigViewPage = 0;

        initView();

        activityRootView = findViewById(R.id.main);
        //获取屏幕高度
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight/3;

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        mHistoryWrongQuesPresenter.getData(isRefresh);
        VpHistoryWrong.setCurrentItem(0);
    }


    /*
    * 初始化界面控件
    * */
    private void initView(){


        mEmptyViewLayout = (EmptyMainLayout) findViewById(R.id.layout_loading);


        /*
        * 答题号按钮菜单相关信息
        * */
        RLayoutAnswerNumberMenu = (RelativeLayout) findViewById(R.id.rlayout_answer_number_menu);
        RLayoutAnswerNumberMenu.setVisibility(View.INVISIBLE);

        /*
        * 返回按钮菜单相关设置
        * */
        TvBack = (TextView) findViewById(R.id.textview_back);
        RLayoutBackMenu = (RelativeLayout) findViewById(R.id.rlayout_back_menu);
//        if(mWrongEntity.getQuesFrom()==0) {
//            TvBack.setText("错题推荐题");
//        }
        RLayoutBackMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    finish();
            }
        });


        /*
        * 提交按钮菜单相关信息
        * */
        RLayoutSubmitMenu = (RelativeLayout) findViewById(R.id.rlayout_submit_menu);
        TvSubmit = (TextView) findViewById(R.id.textview_submit);
        TvSubmit.setVisibility(View.INVISIBLE);

//        IvAssess = (ImageView) findViewById(R.id.iv_assess);

        /*
        * 更多功能按钮菜单相关信息
        * */
        RLayoutMoreFouctionMenu = (RelativeLayout) findViewById(R.id.rlayout_more_fouction_menu);
        RLayoutMoreFouctionMenu.setVisibility(View.INVISIBLE);
        RLayoutMoreFouctionMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(getApplicationContext(),"更多功能菜单",Toast.LENGTH_SHORT).show();
                if(InforHistoryWrongQues!=null) {
                    initPopupWindowMoreFunction();
                }else {
                    Toast.makeText(getApplicationContext(),"数据加载中，请稍后重试...",Toast.LENGTH_SHORT).show();
                }
            }
        });

        /*
        * 计时器显示
        * */
        TvTimeMeter = (TextView) findViewById(R.id.tv_time_meter);
        TvTimeMeter.setVisibility(View.INVISIBLE);

        VpHistoryWrong = (ViewPager) findViewById(R.id.viewpager);

    }

    /*********************
     * ******************
     *实现试卷明细解析
     * *****************
     ******************/
    /************************************************************************************************************************/

    @Override
    public void loadData(List<HistoryWrongQuesJson> data) {
        InforHistoryWrongQues =data;
        Log.e("==size99999==","==InforHistoryWrongQues==="+InforHistoryWrongQues.size());
        PaperInfor.QuesBrief = InforHistoryWrongQues.get(0).getTheme();
        PaperInfor.TypeID = InforHistoryWrongQues.get(0).getTypeID();

        //这里因为是3.0一下版本，所以需继承FragmentActivity，通过getSupportFragmentManager()获取FragmentManager
        //3.0及其以上版本，只需继承Activity，通过getFragmentManager获取事物
        FragmentManager fm = getSupportFragmentManager();
        //初始化自定义适配器MyFragmentPageAdapter
        mAdapter =  new HistoryWrongQuesPaperFragmentAdapter(fm);
        MyOnPageChangeListener myOnPageChangeListener = new MyOnPageChangeListener();
        VpHistoryWrong.setOnPageChangeListener(myOnPageChangeListener);
        //绑定自定义适配器
        VpHistoryWrong.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();

        if(InforHistoryWrongQues!=null){
            RLayoutMoreFouctionMenu.setVisibility(View.VISIBLE);
        }
//        if(data.get(0).getCorrectRate()<0.7) {
//            IvAssess.setBackgroundResource(R.mipmap.review_failed);
//        }else{
//            IvAssess.setBackgroundResource(R.mipmap.review_passed);
//        }

    }

    @Override
    public void loadComplete(boolean hasComplete) {

    }

    @Override
    public void openExamReportDialog() {

    }

    @Override
    public void updatingResult(boolean isSucceed) {

    }

    public LoadingDialog getLoadingDialog(){
        return null;
    }

    @Override
    public RxAppCompatActivity getHolderActivity() {
        return null;
    }


    /************************************************************************************************************************/


    /*
    * LazyViewPage切换事件监听
    * */
    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
//			Log.e("onPageScrolled==111==: ", "==arg0=="+arg0);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
//			Log.e("onPageScrolled==111==: ", "==arg0=="+arg0);
        }

        @Override
        public void onPageSelected(int arg0) {
            PaperInfor.QuesBrief = InforHistoryWrongQues.get(arg0).getTheme();
            PaperInfor.TypeID = InforHistoryWrongQues.get(arg0).getTypeID();

//            if(InforHistoryWrongQues.get(arg0).getCorrectRate()<0.7) {
//                Log.e("==loadData==","==getCorrectRate==000===review_failed==="+arg0);
//                IvAssess.setBackgroundResource(R.mipmap.review_failed);
//            }else{
//                Log.e("==loadData==","==getCorrectRate===111===review_failed==="+arg0);
//                IvAssess.setBackgroundResource(R.mipmap.review_passed);
//            }
        }

    }


    //隐藏虚拟键盘:Fragment进行切换的时候使用
    public  void HideKeyboard() {
        /**隐藏软键盘**/
        View viewK = this.getWindow().peekDecorView();
        if(viewK != null){
            InputMethodManager inputmanger = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(viewK.getWindowToken(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /*
    * 监听系统home事件
    * */
    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        System.out.println("onUserLeaveHint");
    }

    /*
    * 监听系统返回事件
    * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            finish();
        }
        return false;
    }


    /*
    *获取题型
    * f：作文  大Z：听力简答  大S：听力填空  E：听力选择  大X：阅读简答  D：阅读选择  K：阅读判断  Q：阅读填空
    * m：匹配题  大C：完形选择  大O：句子填空   g：翻译题    d：看图写句子  A；单选题
    * */
    private  String getQuesType(int postion){
        String strTypeID = HistoryWrongQuesPaperActivity.InforHistoryWrongQues.get(postion).getTypeID();
        String strQuesTypeName = "";
        if(strTypeID.equals("f")){
            strQuesTypeName = "作文";
        }else if(strTypeID.equals("Z")){
            strQuesTypeName = "听力简答";
        }else if(strTypeID.equals("S")){
            strQuesTypeName = "听力填空";
        }else if(strTypeID.equals("E")){
            strQuesTypeName = "听力选择";
        }else if(strTypeID.equals("X")){
            strQuesTypeName = "阅读简答";
        }else if(strTypeID.equals("D")){
            strQuesTypeName = "阅读选择";
        }else if(strTypeID.equals("K")){
            strQuesTypeName = "阅读判断";
        }else if(strTypeID.equals("Q")){
            strQuesTypeName = "阅读填空";
        }else if(strTypeID.equals("m")){
            strQuesTypeName = "匹配题";
        }else if(strTypeID.equals("C")){
            strQuesTypeName = "完形选择";
        }else if(strTypeID.equals("O")){
            strQuesTypeName = "句子填空";
        }else if(strTypeID.equals("g")){
            strQuesTypeName = "翻译题";
        }else if(strTypeID.equals("d")){
            strQuesTypeName = "看图写句子";
        }else if(strTypeID.equals("A")){
            strQuesTypeName = "单选题";
        }else if(strTypeID.equals("T")){
            strQuesTypeName = "翻译填空";
        }else if(strTypeID.equals("P")){
            strQuesTypeName = "短文填空";
        }else if(strTypeID.equals("N")){
            strQuesTypeName = "词汇填空";
        }
        return  strQuesTypeName;
    }

    /******************************************更多功能popupwindow****************************************************/

    private PopupWindowMoreFunction mPopupWindowMoreFunction;
    private void initPopupWindowMoreFunction(){
        if (mPopupWindowMoreFunction == null) {
            //自定义的单击事件
            OnClickLintener paramOnClickListener = new OnClickLintener();
            mPopupWindowMoreFunction = new PopupWindowMoreFunction(this, paramOnClickListener, Control.dip2px(this,140), Control.dip2px(this,80));
            //监听窗口的焦点事件，点击窗口外面则取消显示
            mPopupWindowMoreFunction.getContentView().setOnFocusChangeListener(new View.OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        mPopupWindowMoreFunction.dismiss();
                    }
                }
            });
        }

        if(!InforHistoryWrongQues.get(currentBigViewPage).getTheme().equals("")) {
            PaperInfor.QuesBrief = InforHistoryWrongQues.get(currentBigViewPage).getTheme();
        }else{
            PaperInfor.QuesBrief = InforHistoryWrongQues.get(currentBigViewPage).getQueList().get(0).getItemContent();
        }
        PaperInfor.QuesID = InforHistoryWrongQues.get(currentBigViewPage).getQuesID();
        PaperInfor.TypeID = InforHistoryWrongQues.get(currentBigViewPage).getTypeID();

        Log.e("======isIsLike========","===00=="+InforHistoryWrongQues.get(currentBigViewPage).isIsLike());
        Log.e("======QuesBrief========","===00=="+PaperInfor.QuesBrief);
        Log.e("======QuesID========","===00=="+PaperInfor.QuesID);
        Log.e("======TypeID========","===00=="+PaperInfor.TypeID);

        //显示当前试题的收藏情况

        if(!InforHistoryWrongQues.get(currentBigViewPage).isIsLike()) {
            PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_unfocus);
            PopupWindowMoreFunction.TvDifficultQuestion.setText("加入收藏");
            PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.white));
        }else if(InforHistoryWrongQues.get(currentBigViewPage).isIsLike()){
            PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_focus);
            PopupWindowMoreFunction.TvDifficultQuestion.setText("取消收藏");
            PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.yellow));
        }

//设置默认获取焦点
        mPopupWindowMoreFunction.setFocusable(true);
//以某个控件的x和y的偏移量位置开始显示窗口
        mPopupWindowMoreFunction.showAsDropDown(RLayoutMoreFouctionMenu, Control.dip2px(this,-120), Control.dip2px(this,15));
//如果窗口存在，则更新
        mPopupWindowMoreFunction.update();
    }
    class OnClickLintener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.layout_dictionary:
                    System.out.println("=======电子词典=========");
                    mPopupWindowMoreFunction.dismiss();
                    startActivity(new Intent(getApplicationContext(), DictionaryActicity.class));
                    break;
                case R.id.layout_difficult_question:
                    System.out.println("=======收藏与否=========");
                    if(!InforHistoryWrongQues.get(currentBigViewPage).isIsLike()) {
                        PaperInfor.IsLike = 1;
                        InforHistoryWrongQues.get(currentBigViewPage).setIsLike(true);
                        PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_focus);
                        PopupWindowMoreFunction.TvDifficultQuestion.setText("取消收藏");
                        PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.yellow));
                    }else if(InforHistoryWrongQues.get(currentBigViewPage).isIsLike()){
                        PaperInfor.IsLike = 0;
                        InforHistoryWrongQues.get(currentBigViewPage).setIsLike(false);
                        PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_unfocus);
                        PopupWindowMoreFunction.TvDifficultQuestion.setText("加入收藏");
                        PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.white));
                    }
                    PaperInfor.QuesID = InforHistoryWrongQues.get(currentBigViewPage).getQuesID();
                    changeStuFavourite();
                    break;

                default:
                    break;
            }

        }

    }


    /*
    * 加入收藏、取消收藏
    * */
    ChangeStuFavouritePresenter mChangeStuFavouritePresenter;
    private void changeStuFavourite(){
        mChangeStuFavouritePresenter = new ChangeStuFavouritePresenter(this,mQuesOrPaperFrom);
        mChangeStuFavouritePresenter.getData(false);
    }


    @Override
    protected void onResume() {
        super.onResume();
        //添加layout大小发生改变监听器
        activityRootView.addOnLayoutChangeListener(this);
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

        if (bottom > oldBottom){
            //输入法软键盘关闭
            Log.d(">>>>>>>>>crg", "输入法软键盘关闭: ");
        } else if (bottom < oldBottom){
            //输入法软键盘打开
            Log.d(">>>>>>>>>crg", "输入法软键盘打开: ");
        }

    }

}